class Solution {
    public static void main(String[] args) {
        int[][] arr =
        {{0,0,0,1,1,1,0,1,0,0} ,
        {1,1,0,0,0,1,0,1,1,1},
        {0,0,0,1,1,1,0,1,0,0},
        {0,1,1,0,0,0,1,0,1,0},
        {0,1,1,1,1,1,0,0,1,0},
        {0,0,1,0,1,1,1,1,0,1},
        {0,1,1,0,0,0,1,1,1,1},
        {0,0,1,0,0,1,0,1,0,1},
        {1,0,1,0,1,1,0,0,0,0},
        {0,0,0,0,1,1,0,0,0,1}};
        System.out.println(numEnclaves(arr));
    }
    public static int numEnclaves(int[][] grid) {
        int n = grid.length ;
        int m = grid[0].length ; 
        boolean[][] f = new boolean[n][m] ; 
        boolean[][] g=  new boolean[n][m] ; 
        for(int i=0 ; i< n;  i ++){
            for(int j=0 ;j<m ; j++){
                if(i==0 || j==0){
                    f[i][j] = grid[i][j]==1?true: false;
                }else{
                  f[i][j] = false ;
                  if(grid[i][j] == 1){
                    f[i][j] = f[i][j-1] || f[i-1][j] ; 
                  }
                }
            }
        }
        for(int i=n-1 ; i>=0 ; i --){
            for(int j=m-1; j>=0 ; j--){
                if(i==n-1 || j==m-1){
                 g[i][j] = grid[i][j] ==1? true : false ;
                }else{
                  g[i][j] = false ;
                  if(grid[i][j] == 1){
                    g[i][j] = g[i+1][j] || g[i][j+1] ; 
                  }
                }
            }
        }
        int sum = 0 ;
        for(int i=0 ; i<n ; i ++){
            for(int j=0 ; j<m ; j++){
                if(grid[i][j] == 1 && (f[i][j]==false && g[i][j]==false)){
                    sum ++ ;
                }
            }
        }
      return sum ;
    }
}